/*
 * @Author: zhangyukele
 * @Date: 2019-09-25 10:10:36
 * @LastEditors: zhangyukele
 * @LastEditTime: 2019-09-25 15:05:15
 * @Description: 重复点击组件
 */
import React, { Component } from 'react'
import { Text, View, TouchableOpacity,StyleSheet } from 'react-native'
import PropTypes from 'prop-types'


export default class BD_noRepeat extends Component {
  static propTypes = {
    flagType:  PropTypes.oneOf(['time', 'api']), //重复点击类型 time 时间类型  api 接口类型 对应的pressHandler必须返回一个Promise对象
    timeInterval: PropTypes.number,  // 重复点击间隔时间(s)
    pressHandler: PropTypes.func, //点击操作函数
    wrapStyle: PropTypes.oneOfType([ //包裹层的样式
      PropTypes.array,
      PropTypes.object,
    ]), 
    children: PropTypes.node, //node组件
  }

  static defaultProps = {
    flagType: 'time',
    timeInterval: 1,
    wrapStyle: {},
    pressHandler: ()=>{},
    children: <></>
  }
  constructor (props) {
    super(props);
    this.state = {

    }
    this.repeatFlag = true //是否可点击标识符 true 可点击
    this.lessTime = props.timeInterval //剩余倒计时
    this.timer = null; //倒计时定时器
  }

  
  handlePress = ()=>{
    const {flagType,pressHandler} = this.props;
    console.log(123);
    //不可点击直接返回
    if(!this.repeatFlag){
      return;
    }
    //关闭标识
    this.repeatFlag = false;
    if(flagType === 'time') {   
      console.log('time');
      //设置定时器
      this.timer = setInterval(() => {
        if(this.flagType){
          this.flagType --;
        }else{
          //打开标识
          this.repeatFlag = true;
        }
      }, this.lessTime * 1000);
      this.props.pressHandler()

    }else if(flagType === 'api'){
      console.log('api');
      //处理api请求类型的
      this.props.pressHandler().then(data => {
        this.repeatFlag = true
      })
    }
    
  }

  setStyle(){
    const {wrapStyle} = this.props;
    let wraps;
    //是数组的情况
    if(Array.isArray(wrapStyle)){
      wraps= wrapStyle
    }else{
      wraps= [wrapStyle]
    }

    return wraps
  }

  render() {
    const {children} = this.props;
    return (
      <TouchableOpacity style={[styles.wraps,...this.setStyle()]} onPress={this.handlePress}>
        {children}
      </TouchableOpacity>
    )
  }
}

const styles = StyleSheet.create({
  wraps: {
    // backgroundColor: 'blue',
    minWidth: 40,
    minHeight: 40,
    justifyContent: 'center',
    // alignItems:"center"
  }
})
